package com.taotao.chatbot.controller;

import com.taotao.chatbot.domain.ChatMessageRequest;
import com.taotao.chatbot.domain.MedMessageLog;
import com.taotao.chatbot.service.ChatService;
import com.taotao.common.core.domain.Result;
import com.taotao.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天控制器
 */
@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    /**
     * 保存聊天消息
     */
    @PostMapping("/message")
    public Result saveMessage(@RequestBody ChatMessageRequest request) {

        if (StringUtils.isEmpty(request.getTraceNo())) {
            return Result.error("支付流水号不能为空");
        }

        try {
            chatService.saveMessage(request);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存聊天记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取聊天记录
     */
    @GetMapping("/history")
    public ResponseEntity<List<MedMessageLog>> getChatHistory(@RequestParam("medicalRecordId") Long medicalRecordId) {
        List<MedMessageLog> history = chatService.getChatHistory(medicalRecordId);
        return ResponseEntity.ok(history);
    }

    /**
     * 验证医生身份
     */
    @PostMapping("/validate-doctor")
    public ResponseEntity<?> validateDoctor(@RequestBody Map<String, String> params) {
        String realName = params.get("username");
        Long doctorId = chatService.validateDoctor(realName);

        Map<String, Object> result = new HashMap<>();
        result.put("valid", doctorId != null);
        result.put("doctorId", doctorId);
        return ResponseEntity.ok(result);
    }

    /**
     * 更新问诊状态
     */
    @GetMapping("/medical/records/{medicalRecordId}/{status}")
    public Result updateConsultationStatus(@PathVariable String medicalRecordId, @PathVariable int status){
        chatService.updateConsultationStatus(medicalRecordId, status);
        return Result.success();
    }


    /**
     * 获取问诊状态
     */
    @GetMapping("/medical/getStatus/{medicalRecordId}")
    public Result<Integer> getConsultationStatus(@PathVariable String medicalRecordId){

        return Result.success(chatService.getStatus(medicalRecordId));
    }
}
